package com.vhly.ddxdecompiler.dexreader.file.mixeditem;

import com.vhly.ddxdecompiler.dexreader.file.DexFile;
import com.vhly.ddxdecompiler.dexreader.file.StringIdsSection;
import com.vhly.ddxdecompiler.dexreader.file.TypeIdsSection;
import com.vhly.ddxdecompiler.dexreader.file.constant.CstConstant;

import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 2009-10-20
 * Time: 23:09:06
 * Platform: Mac OS X 10.5.8
 *
 * @author vhly[FR]
 */
public class Annotation {
    int typeIndex;
    Vector<NameValuePair> pairs;

    private TypeIdItem type;

    public Annotation() {
        pairs = new Vector<NameValuePair>();
    }

    public void reloc(DexFile dex) {
        TypeIdsSection types = dex.getTypeIds();
        type = types.indexOf(typeIndex);
        int size = pairs.size();
        Vector<NameValuePair> v1 = pairs;
        NameValuePair pair;
        StringIdsSection strings = dex.getStringIds();
        for (int i = 0; i < size; i++) {
            pair = v1.elementAt(i);
            pair.name = strings.indexOf(pair.nameIndex);
            Object value = pair.value;
            if (value instanceof CstConstant) {
                CstConstant cc = (CstConstant) value;
                cc.reloc(dex);
            } else if (value instanceof Object[]) {
                Object[] arr = (Object[]) value;
                int length = arr.length;
                Object o1;
                for (int j = 0; j < length; j++) {
                    o1 = arr[j];
                    reloc(dex, o1);
                }
            }
        }
    }

    private void reloc(DexFile dex, Object o1) {
        if (o1 instanceof CstConstant) {
            CstConstant cc = (CstConstant) o1;
            cc.reloc(dex);
        } else if (o1 instanceof Object[]) {
            Object[] arr = (Object[]) o1;
            int length = arr.length;
            Object o2;
            for (int j = 0; j < length; j++) {
                o2 = arr[j];
                reloc(dex, o2);
            }
        } else if(o1 instanceof Annotation){
            Annotation anno = (Annotation) o1;
            anno.reloc(dex);
        }
    }

    public TypeIdItem getType() {
        return type;
    }

    public NameValuePair findByName(String key){
        NameValuePair ret = null;
        if(!pairs.isEmpty()){
            for(NameValuePair pair : pairs){
                if(pair.getName().equals(key)){
                    ret = pair;
                    break;
                }
            }
        }
        return ret;
    }
}
